<?php

namespace app\modules\prod\controllers;

use yii;
use yii\helpers\Json;
use app\common\Controller;
use app\common\SystemEvent;
use yii\helpers\ArrayHelper;
use yii\web\ForbiddenHttpException;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\Response;
use yii\widgets\ActiveForm;
use yii2mod\editable\EditableAction;
use yii2mod\rbac\filters\AccessControl;
use app\models\Region;
use app\models\RegionType;
use app\models\ProdSpec;
use app\models\ProdInst;
use app\models\ProdAttrInst;
use app\models\Cust;
use app\models\CustSearch;
use app\models\ProdAttrSpecRela;
use app\models\CustExternalAttr;
use app\models\OrderExternalAttr;
use app\models\UploadForm;
use app\models\Image;

use app\models\Order;
use app\models\CustSource;

use app\models\OrderResumes;

use app\models\OrderSearch;
//use kartik\file\FileInput;
use yii\web\UploadedFile;

use app\models\Domain;
use yii\data\Pagination;
use yii\data\ActiveDataProvider;
use yii\helpers\Html;
use app\common\Functions;

class CustController extends Controller
{
    
	public $module;
	public $protected_uids = [];    
	public $superadmin_uid = 0;
	public $loginRedirect = '/admin/dashboard';
	public $defaultAction = 'index';
	public function init()
	{
		parent::init();
	}


     public function actionIndex($q)
    {
        $query = Region::find();
        $pagination = new Pagination([
            'defaultPageSize' => 5,
            'totalCount' => $query->count(),
        ]);
        $regions = $query->orderBy('region_type_id')->offset($pagination->offset)->limit($pagination->limit)->all();
        return $this->render('index', ['pagination' => $pagination ,
        'regions' => $regions ]);

    }


    public function actionSeachprodinst($q)
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $out = ['results' => ['id' => '', 'text' => '']];
        if (!$q) {
            return $out;
        }

        $data = ProdInst::find()
            ->select('id, prod_name as text')
            ->where(['prod_spec_id'=>10001])
            ->andFilterWhere(['like', 'prod_name', $q])
            ->limit(12)
            ->asArray()
            ->all();

        $out['results'] = array_values($data);

        return $out;
    }

    public function actionView($id=null, $attr_type_spec_id=null, $prod_spec_name = null, $order_id = null, $acc_nbr = null)
    {
        $topShowCnt = 0;
        $topShowss = [];
        $attrOrderSpecNames = [];

        // 取出标题配置， 是楼盘还是房源 还是其它
        $prodSpecName = $prod_spec_name;

        $model = $this->getCust($id);

        $query = Order::find()->alias('a');
        $query->where(['a.id' => $order_id ]);
        $orderModel = $query->one();
        foreach($orderModel->externalAttrs as $attrSpec)
        {
            $orderModel->attrSpecs[$attrSpec->attr_spec_id] = $attrSpec->content;
        }

        // 获取到对应图片的全部URL
        $p1 = $this->getAttrInstByID($id );

        //  查询所有该产品的特性值规格，主要用来取名称
        $attrSpecs = $this->getAttrSpecs($attr_type_spec_id);
        $attrSpecNames = [];
        foreach ($attrSpecs as $attrSpec)
        {
            $attrSpecNames[$attrSpec->attrSpecs->attr_spec_id]['name'] = $attrSpec->attrSpecs->attr_spec_name;
            $attrSpecNames[$attrSpec->attrSpecs->attr_spec_id]['attr_spec_type_id'] = $attrSpec->attrSpecs->attr_spec_type_id;

        }

         //  如果是 客源的话需要查询对应的订单属性
        if ($order_id!=null)
        {
            $attrOrderSpecs     = $this->getAttrSpecs('30001');

            foreach ($attrOrderSpecs as $attrSpec)
            {
                $attrOrderSpecNames[$attrSpec->attrSpecs->attr_spec_id]['name'] = $attrSpec->attrSpecs->attr_spec_name;
                $attrOrderSpecNames[$attrSpec->attrSpecs->attr_spec_id]['attr_spec_type_id'] = $attrSpec->attrSpecs->attr_spec_type_id;

            }

        }

        //  获取2级的区域名称
        $regionList = $this->getParentRegionTypes(0);

        $topShows[$topShowCnt]['field_name']    = '客户类型';
        $topShows[$topShowCnt]['field_values']  = Functions::getDomainsName('cust','cust_type_id', $model->cust_type_id )  ;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    = '客户状态';
        $topShows[$topShowCnt]['field_values']  = Functions::getDomainsName('cust','state', $model->state ) ;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    = '客户来源';
        $topShows[$topShowCnt]['field_values']  = Functions::getDomainsName('cust','cust_source_id',  $model->cust_source_id) ;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    = '客户地址';
        $topShows[$topShowCnt]['field_values']  = $model->cust_address ;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    = '客户描述';
        $topShows[$topShowCnt]['field_values']  = $model->remark;
        $topShowCnt++;


        $topShows[$topShowCnt]['field_name']    = '创建用户';
        $topShows[$topShowCnt]['field_values']  = $model->users->username;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    = '创建时间';
        $topShows[$topShowCnt]['field_values']  = $model->create_date;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    = '修改用户';
        $topShows[$topShowCnt]['field_values']  = $model->modifyUsers->username;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    =  '修改时间';
        $topShows[$topShowCnt]['field_values']  = $model->modify_date;
        $topShowCnt++;

        $topShows[$topShowCnt]['field_name']    =  '状态';
        $topShows[$topShowCnt]['field_values']  = $model->state;
        $topShowCnt++;

        if ($acc_nbr!=$model->tel)
        {
            $model->tel = "******";
        }



        return $this->render('view',
            ['model' => $model,
                'orderModel' => $orderModel,
                'p1' =>$p1,
                'order_id' =>$order_id,
                'attrSpecNames' => $attrSpecNames,
                'attrOrderSpecNames' => $attrOrderSpecNames,
                'topShows' => $topShows,
                'attr_type_spec_id' =>$attr_type_spec_id,
                'attrSpecs' => $attrSpecs,
                'regionList' =>$regionList,
                'prodSpecName' =>$prodSpecName,
                'update'=>1]);
    }

    public function getOrderList($order_id =null)
    {


        //$model = new Order();

        $query3 = Order::find()->alias('a');
        $query3->joinWith('staffs  AS b');

        $query3->joinWith('externalAttrs  AS e');
        $query3->where(['a.id' => $order_id ]);

        $model = $query3->one();


        //  查询所有该产品的特性值
        $attrSpecs = $this->getAttrSpecs(30001);

        // 构建查询索引，让产品特性实例可以通过类型进行进一步的数据查询
        $attrSpecIndex = [];
        $p1 = $this->getAttrInstByID($order_id );

        // 先把order取出来
        $fileCnt = 0;
        foreach ($attrSpecs as $attrSpec)
        {
            $attrSpecIndex[$attrSpec->attrSpecs->attr_spec_id]['name']                = $attrSpec->attrSpecs->attr_spec_name;
            $attrSpecIndex[$attrSpec->attrSpecs->attr_spec_id]['attr_spec_type_id'] = $attrSpec->attrSpecs->attr_spec_type_id;
        }

        $model->staffName         =  $model->staffs->staff_name;
        foreach($model->externalAttrs as $prodAttrInst)
        {
            $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['id']                    = $prodAttrInst->id;
            $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['content']              = $prodAttrInst->content;
            $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['content2']             = $prodAttrInst->content2;
            $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['attrSpecTypeID']      = $attrSpecIndex[$prodAttrInst->attr_spec_id]['attr_spec_type_id'];
        }

//        foreach ( $model2 as $prodinst)
//        {
//
//            $model->staffName         =  $prodinst->staffs->staff_name;
//            $model->region_id         = $prodinst->region_id ;
//            $model->id                  = $prodinst->id ;
//            $model->order_number      = $prodinst->order_number ;
//            $model->object_id          = $prodinst->object_id  ;
//            $model->object_type_id    = $prodinst->object_type_id ;
//            $model->order_type_id     = $prodinst->order_type_id;
//            $model->state              = $prodinst->state;
//            $model->staff_id           = $prodinst->staff_id ;
//            $model->remark              = $prodinst->remark;
//
//            foreach($prodinst->externalAttrs as $prodAttrInst)
//            {
//                $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['id']                    = $prodAttrInst->id;
//                $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['content']              = $prodAttrInst->content;
//                $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['content2']              = $prodAttrInst->content2;
//                $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['attrSpecTypeID']      = $attrSpecIndex[$prodAttrInst->attr_spec_id]['attr_spec_type_id'];
//            }
//
//
//            break;
//        }

        return $model;
    }

    /*
     *  更新内容
     * */
    public function actionUpdate($id=null, $attr_type_spec_id=null, $prod_spec_name = null, $parent_prod_id = null, $order_id =nulll, $last_url = null)
    {

        $attr_type_spec_id = 20001;
        $domainTypes = [];
        $domainSources = [];

        // 初始化最重要的产品实例字段
        $postModel      = new Cust();

        $postOrderModel = new Order();

        // 初始化全部的图片
        $uploadModel = new UploadForm();






        // 取出标题配置， 是楼盘还是房源 还是其它
        $prodSpecName = $prod_spec_name;
        //ProdSpec::find()->select(['spec_name'])->where(['id' => $prod_spec_id])->one();

        //取到产品实例数据

  //  $model = $this->findModel($id);
        //$model = new Cust();
        $query3 = Cust::find()->alias('a');

        $query3->joinWith('regions  AS b');
        $query3->joinWith('parentRegions  AS c');



        $query3->joinWith('custExternalAttrs  AS e');
        $query3->where(['a.id' => $id ]);

        $model = $query3->one();



        //  查询所有该产品的特性值
        $attrSpecs = $this->getAttrSpecs($attr_type_spec_id);

        // 构建查询索引，让产品特性实例可以通过类型进行进一步的数据查询
        $attrSpecIndex = [];


        $p1 = $this->getAttrInstByID($id );



        $fileCnt = 0;
        foreach ($attrSpecs as $attrSpec)
        {
            $attrSpecIndex[$attrSpec->attrSpecs->attr_spec_id]['name']                = $attrSpec->attrSpecs->attr_spec_name;
            $attrSpecIndex[$attrSpec->attrSpecs->attr_spec_id]['attr_spec_type_id'] = $attrSpec->attrSpecs->attr_spec_type_id;
        }


        foreach($model->custExternalAttrs as $prodAttrInst)
        {
            $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['id']                    = $prodAttrInst->id;
            $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['content']              = $prodAttrInst->content;
            $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['content2']             = $prodAttrInst->content2;
            $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['attrSpecTypeID']      = $attrSpecIndex[$prodAttrInst->attr_spec_id]['attr_spec_type_id'];
        }

//        foreach ( $model2 as $prodinst)
//        {
//
//
//            $model->id              = $prodinst->id ;
//            $model->cust_type_id  = $prodinst->cust_type_id ;
//            $model->cust_name      = $prodinst->cust_name ;
//            $model->province       = $prodinst->parentRegions->parent_region_id;
//            $model->city            = $prodinst->parentRegions->id;
//            $model->areas           = $prodinst->areas ;
//            $model->region_id       = $prodinst->region_id ;
//            $model->cust_source_id  = $prodinst->cust_source_id;
//
//            foreach($prodinst->custExternalAttrs as $prodAttrInst)
//            {
//                $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['id']                    = $prodAttrInst->id;
//                $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['content']              = $prodAttrInst->content;
//                $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['content2']              = $prodAttrInst->content2;
//                $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['attrSpecTypeID']      = $attrSpecIndex[$prodAttrInst->attr_spec_id]['attr_spec_type_id'];
//            }
//
//
//            break;
//        }

        $model->parentCustSourceID = $this->getParentCustSources($model->cust_source_id);


        // 获取现有的对应的订单 以及订单的attr属性
        $orderModel = $this->getOrderList($order_id);


        if (   $postModel->load(Yii::$app->request->post())
            && $postOrderModel->load(Yii::$app->request->post())
            && $postModel->validate()
            && $postOrderModel->validate())
        {
            $postModel->modify_date        = date("Y-m-d H:i:s",time());;
            $postModel->modify_staff_id   = Yii::$app->user->id;

            //更新prod_inst
            $this->insertOrUpdateToCustTable($postModel, $model, $postOrderModel, $orderModel);

            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));

//            return $this->redirect(['classify','attr_type_spec_id' =>$attr_type_spec_id]);


            if ($last_url)
            {
                return $this->redirect($last_url);
            }

            return $this->redirect(Yii::$app->request->referrer);
        }



        //  获取2级的区域名称
        $regionList = $this->getParentRegionTypes(0);

        //$regionList      = $query2->orderBy('id')->all();


        $domainTypes   = $this->getDomains('cust', 'cust_type_id');
        $domainSources = $this->getDomains('cust', 'cust_source_id');

        // 查询所有该产品的特性规格
        $attrSpecs         = $this->getAttrSpecs($attr_type_spec_id);
        $orderAttrSpecs    = $this->getAttrSpecs('30001');

        // 父区域编码
        $parent_region_id = 0;

        $regionList      = $this->getParentRegionTypes($parent_region_id);


        // 客户来源清单
        $custSources       = $this->getCustSources(-1);


        return $this->render('update',
            [
                'custSources'  =>$custSources,
                'orderModel'  =>$orderModel,
                'orderAttrSpecs'  => $orderAttrSpecs,
                'domainTypes'  => $domainTypes,
                'domainSources' => $domainSources,
                'parent_prod_id' => $parent_prod_id,
                'p1' =>$p1,
                'model' => $model,
                'uploadModel' => $uploadModel,
                'attr_type_spec_id' =>$attr_type_spec_id,
                'attrSpecs' => $attrSpecs,
                'regionList' =>$regionList,

                'update'=>1]);
    }

    public function getAttrSpecs($prod_spec_id)
    {
        $attrSpecRela = ProdAttrSpecRela::find()->alias('f');
        $attrSpecRela->joinWith('attrSpecs  AS g');
        $attrSpecRela->orderBy('sort');
        $attrSpecs    = $attrSpecRela->where(['f.prod_spec_id' => $prod_spec_id ])->all();
        return $attrSpecs;
    }

    public function getParentCustSources($cust_source_id )
    {
        $custSource = CustSource::find()->where(['id'=>$cust_source_id])->orderBy('sort')->one();

        if ($custSource)
        {
            return $custSource->parent_source_id;
        }
        return 0;

    }

    public function getCustSources($parent_source_id )
    {
        $mapCustSource = [];

        $query = CustSource::find()->alias('f');
//        $query->joinWith('attrSpecs  AS g');
        $query->orderBy('sort');
        $custSources    = $query->where(['f.parent_source_id' => $parent_source_id ])->orderBy('sort')->all();


        foreach ($custSources as $custSource)
        {
            $mapCustSource[$custSource->id] = $custSource->cust_source_name;
        }

        return $mapCustSource;
    }




    public function getCustSourceTypeIDCnt($cust_source_id)
    {
        switch ($cust_source_id)
        {
            case 101:
                Yii::trace("201");
                return 'futureCust';


            case 102:
                Yii::trace("202");
                return 'intentionCust';





            default:
                Yii::trace("default");
                return'noTypeCust';

        }
    }

    public function getCustTypeIDCnt($cust_type_id)
    {
        switch ($cust_type_id)
        {
            case 101:

                return 'futureCust';


            case 102:

                return 'intentionCust';


            case 103:

                return 'dealCust';


            case 104:

                return 'lossCust';


            default:

                return'noTypeCust';

        }
    }

    //  拼凑头部信息
    public function getCustTypeIDCnts()
    {
        $custInfo = [];
        $sourceCounts = [];

        $sql  = 'SELECT count(*) custTypeIDCnt, cust_type_id cust_source_id  FROM  ';
        $sql .= Cust::tableName();
        $sql .= ' group by cust_type_id';

        $typeCounts = Yii::$app->db->createCommand($sql)->queryAll();



        $custInfo['noTypeCust'] = 0;
        $custInfo['futureCust'] = 0;
        $custInfo['intentionCust'] = 0;
        $custInfo['dealCust'] = 0;
        $custInfo['lossCust'] = 0;

        foreach ($typeCounts as $typeCount)
        {
            $custInfo[$this->getCustTypeIDCnt($typeCount['cust_source_id'])] += $typeCount['custTypeIDCnt'];

        }

        return $custInfo;

    }

    //  拼凑头部信息
    public function getCustSourceTypeIDCnts()
    {
        $custInfo = [];
        $sourceCounts = [];

        $sql  = 'SELECT count(*) custSourceTypeIDCnt, cust_source_id cust_source_id  FROM  ';
        $sql .= Cust::tableName();
        $sql .= ' group by cust_source_id';

        $sourceCounts = Yii::$app->db->createCommand($sql)->queryAll();

        Yii::trace("******************************************");
           Yii::trace($sourceCounts);

         $custInfo['noTypeCust'] = 0;
         $custInfo['futureCust'] = 0;
         $custInfo['intentionCust'] = 0;
         $custInfo['dealCust'] = 0;
         $custInfo['lossCust'] = 0;

        foreach ($sourceCounts as $sourceCount)
        {
            $custInfo[$this->getCustSourceTypeIDCnt($sourceCount['cust_source_id'])] += $sourceCount['custSourceTypeIDCnt'];
//            switch ($sourceCount['cust_source_id'])
//            {
//                case 101:
//                    $custInfo['futureCust'] = $sourceCount['custSourceTypeIDCnt'];
//                    break;
//
//                case 102:
//                    $custInfo['intentionCust'] = $sourceCount['custSourceTypeIDCnt'];
//                    break;
//
//                case 103:
//                    $custInfo['dealCust'] = $sourceCount['custSourceTypeIDCnt'];
//                    break;
//
//                case 104:
//                    $custInfo['lossCust'] = $sourceCount['custSourceTypeIDCnt'];
//                    break;
//
//                default:
//                    $custInfo['noTypeCust'] = $sourceCount['custSourceTypeIDCnt'];
//                    break;
//            }
        }

        return $custInfo;

    }



    public function actionCustsource($parent_cust_source_id, $cust_source_id=null)
    {
        $custSources = $this->getCustSources( $parent_cust_source_id);


        if ($cust_source_id)
        {
            foreach($custSources as $value=>$name)
            {
                if ($cust_source_id==$value)
                {
                    echo Html::tag('option',Html::encode($name), ['value'=>$value]) ;
                    break;
                }

            }
        }
        else
        {
            echo Html::tag('option','选择来源', ['value'=>'empty']) ;
        }




        foreach($custSources as $value=>$name)
        {
            echo Html::tag('option',Html::encode($name),array('value'=>$value));
        }
    }

    public function actionTenantmng()
    {
        $tenant = 1;
        return $this->actionCustsgrid($tenant);
    }

    public function actionMycust()
    {
        $tenant = 1;
        $user_id = Yii::$app->user->id;
        return $this->actionCustsgrid($tenant, $user_id);
    }

    public function actionCustsgrid($tenant=null, $user_id=null ,$parent_id=null)
    {
        $domainTypes = [];
        $domainSources = [];

        $attr_type_spec_id = 20001;
//        if ($attr_type_spec_id==null)
//        {
//            $attr_type_spec_id = 1;
//        }

        // 取出标题配置， 是楼盘还是房源 还是其它
        // $prodSpec = ProdSpec::find()->select(['spec_name'])->where(['prod_spec_id' => $prod_spec_id])->one();
        $prodSpecName ='客户';

        // 查询所有该产品的特性值
        $attrSpecs    = $this->getAttrSpecs($attr_type_spec_id);


        // 取出区域编码对应的文字
        $regionTypes = $this->getRegionTypes();


        $domainTypes   = $this->getDomains('cust', 'cust_type_id');
        $domainSources = $this->getDomains('cust', 'cust_source_id');


        $where=[];
        $where['parent_id']=$parent_id;//大楼ID

//        Yii::trace("=====================              ============");
//        Yii::trace($where['parent_id']);

        $searchModel = new CustSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams,$user_id ,$where);




        $today = date("Y-m-d",time());
        $regionTodayCnt = Cust::find()->where(['AND',['>','modify_date',$today] ])->count();
        $regionCnt      = Cust::find()->groupBy(['region_id'])->count();


        // 获取客户分组
        $custInfo = [];
        $custInfo = $this->getCustTypeIDCnts();

//        $custInfo['noTypeCust'] = 1;
//        $custInfo['futureCust'] = 1;
//        $custInfo['intentionCust'] = 1;
//        $custInfo['dealCust'] = 1;
//        $custInfo['lossCust'] = 1;
        //$custInfo['totalCust'] = 1;
        // renderAjax
        //renderPartial
// 获取当前的url $last_url
        $now_url = Yii::$app->request->getUrl();


        //跟进中客户数
        $where['state']=30001;
        $dataState = $searchModel->search(Yii::$app->request->queryParams,$user_id ,$where);
        //本月招商面积
        $acreage=$this->getTotalLendedAreas($parent_id); //已租面积


        if ($tenant){
            return $this->render('tenantmng',
                [
                    'now_url'  => $now_url,
                    'domainTypes'  => $domainTypes,
                    'domainSources' => $domainSources,
                    'custInfo' => $custInfo,
                    'attr_type_spec_id' => $attr_type_spec_id,
                    'prodSpecName' =>$prodSpecName,
                    'regionTypes' => $regionTypes,
                    'dataProvider' => $dataProvider,
                    'searchModel' =>  $searchModel,
                    'regionCnt' => $regionCnt,
                    'attrSpecs' => $attrSpecs,
                    'regionTodayCnt' => $regionTodayCnt]);
        }else{
            return $this->renderAjax('custmng',
                [
                    'now_url'  => $now_url,
                    'domainTypes'  => $domainTypes,
                    'domainSources' => $domainSources,
                    'custInfo' => $custInfo,
                    'attr_type_spec_id' => $attr_type_spec_id,
                    'prodSpecName' =>$prodSpecName,
                    'regionTypes' => $regionTypes,
                    'dataProvider' => $dataProvider,
                    'searchModel' =>  $searchModel,
                    'regionCnt' => $regionCnt,
                    'attrSpecs' => $attrSpecs,
                    'regionTodayCnt' => $regionTodayCnt,
                    'dataState' =>$dataState,
                    'acreage' =>$acreage]);
        }

        //return $this->renderPartial('custgrid', ['time' => date('H:i:s')]);

    }


    // 获取商圈所属楼盘已租面积
    public function getTotalLendedAreas($tradingAreaID=null)
    {
        //数据初始化
        $sumContent = 0;
        // 先取出父id对应的规格标识
        $query = ProdInst::find()->alias('f');


        $parentProdInst  = $query->where(['f.id' => $tradingAreaID ])->one();

        $sql  = 'SELECT sum(truncate(content,2)) as sumContent FROM  ';
        $sql .= ProdAttrInst::tableName();
        $sql .= ' as a, ';
        $sql .= ProdInst::tableName() ;

        $sql .= ' as b WHERE a.attr_spec_id =:attr_spec_id AND a.prod_id = b.id and b.prod_spec_id = :prod_spec_id and b.state = :state and b.parent_id=:parent_id  and b.modify_date<=:b and b.modify_date>=:a ';

        //本月
        $a= date("Y-m-d H:i:s",mktime(0, 0 , 0,date("m"),1,date("Y")));
        $b= date("Y-m-d H:i:s",mktime(23,59,59,date("m"),date("t"),date("Y")));

        $lendedAreas = Yii::$app->db->createCommand($sql)
            ->bindValue(':attr_spec_id', 8)
            ->bindValue(':prod_spec_id', '10002')
            ->bindValue(':state', '1002')
            ->bindValue(':parent_id', $tradingAreaID)
            ->bindValue(':a', $a)
            ->bindValue(':b', $b)
            ->queryOne();
        $sumContent = $lendedAreas['sumContent'];


        if ($sumContent)
        {
            return $sumContent;
        }
        $sumContent = 0;

        return $sumContent;

    }




    /*
     * @p prod_spec_id 产品规格
     *
     * */
    public function actionClassify($attr_type_spec_id=null)
    {

        if ($attr_type_spec_id==null)
        {
            $attr_type_spec_id = 1;
        }

        // 取出标题配置， 是楼盘还是房源 还是其它
       // $prodSpec = ProdSpec::find()->select(['spec_name'])->where(['prod_spec_id' => $prod_spec_id])->one();
        $prodSpecName ='客户';

        // 查询所有该产品的特性值
        $attrSpecs    = $this->getAttrSpecs($attr_type_spec_id);


        // 取出区域编码对应的文字
        $regionTypes = $this->getRegionTypes();



        $searchModel = new CustSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);



        $today = date("Y-m-d",time());
        $regionTodayCnt = Cust::find()->where(['AND',['>','modify_date',$today] ])->count();
        $regionCnt      = Cust::find()->groupBy(['region_id'])->count();



        return $this->render('classify',
            [
                'attr_type_spec_id' => $attr_type_spec_id,
                'prodSpecName' =>$prodSpecName,
                'regionTypes' => $regionTypes,
                'dataProvider' => $dataProvider,
                'searchModel' =>  $searchModel,
                'regionCnt' => $regionCnt,
                'attrSpecs' => $attrSpecs,
                'regionTodayCnt' => $regionTodayCnt]);

    }

    // 创建子集
    //public function actionCreateSub($region_type_id=null,$region_type_name=null)

    public function actionCreatemodal($attr_type_spec_id=null, $parent_prod_id = null, $last_url=null)
    {
        $domainTypes = [];
        $domainSources = [];

        // 初始化类型
        $model = new Cust();

        if ($model->load(Yii::$app->request->post()) && $model->validate())
        {
            //Yii::trace("=====================              ============");
//            Yii::trace($model);
//            Yii::trace($model->parent_id);


            // $model->parent_region_id  = 0;
            $model->create_date        = date("Y-m-d H:i:s",time());;
            $model->create_staff_id   = Yii::$app->user->id;
            $model->modify_date        = date("Y-m-d H:i:s",time());;
            $model->modify_staff_id   = Yii::$app->user->id;
            $model->input_time        = date("Y-m-d H:i:s",time());;
            $model->state               = '301';

            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));

            //创建Region
            $this->insertOrUpdateToCustTable($model);
            return $this->redirect(  $last_url);

            return;
            //return Yii::$app->request->getReferrer();
            // return $this->redirect(['classify','attr_type_spec_id' =>$attr_type_spec_id]);

        }

        // 查询所有该产品的特性规格
        $attrSpecs    = $this->getAttrSpecs($attr_type_spec_id);

        // 父区域编码
        $parent_region_id = 0;

        $regionList      = $this->getParentRegionTypes($parent_region_id);


        $p1 = [];

        // 初始化全部的图片
        $uploadModel = new UploadForm();


        $domainTypes   = $this->getDomains('cust', 'cust_type_id');
        $domainSources = $this->getDomains('cust', 'cust_source_id');

        return $this->renderAjax('createmodal',
            [
                'domainTypes'  => $domainTypes,
                'domainSources' => $domainSources,
                'parent_prod_id' => $parent_prod_id,
                'p1' =>$p1,
                'model' => $model,
                'uploadModel' => $uploadModel,
                'attr_type_spec_id' =>$attr_type_spec_id,
                'attrSpecs' => $attrSpecs,
                'regionList' =>$regionList]);
    }

    public function actionUpdatemodal($cust_id=null,$attr_type_spec_id=null, $parent_prod_id = null, $last_url=null)
    {
        $p1 = [];
        $domainTypes = [];
        $domainSources = [];

        // 初始化最重要的产品实例字段
        $postModel   = new Cust();

        $query3 = Cust::find()->alias('a');
        $query3->joinWith('regions  AS b');
        $query3->joinWith('parentRegions  AS c');
        $query3->joinWith('custExternalAttrs  AS e');
        $query3->where(['a.id' => $cust_id ]);

        $model2 = $query3->all();

        // 查询所有该产品的特性规格
        $attrSpecs    = $this->getAttrSpecs(20001);

        // 构建查询索引，让产品特性实例可以通过类型进行进一步的数据查询
        $attrSpecIndex = [];


        $p1 = $this->getAttrInstByID($cust_id );

        $model = new Cust();
        foreach ( $model2 as $prodinst)
        {


            $model->id              = $prodinst->id ;
            $model->cust_type_id  = $prodinst->cust_type_id ;
            $model->cust_name      = $prodinst->cust_name ;
            $model->province       = $prodinst->parentRegions->parent_region_id;
            $model->city            = $prodinst->parentRegions->id;
            $model->areas           = $prodinst->areas ;
            $model->region_id       = $prodinst->region_id ;
            $model->state       = $prodinst->state ;
            $model->cust_source_id        = $prodinst->cust_source_id  ;

            $model->remark       = $prodinst->remark ;
            $model->cust_address       = $prodinst->cust_address;

            foreach($prodinst->custExternalAttrs as $prodAttrInst)
            {
                $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['id']                    = $prodAttrInst->id;
                $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['content']              = $prodAttrInst->content;
                $model->localAttrsInsts[$prodAttrInst->attr_spec_id]['attrSpecTypeID']      = $attrSpecIndex[$prodAttrInst->attr_spec_id]['attr_spec_type_id'];
            }


            break;
        }



        if ($postModel->load(Yii::$app->request->post()) && $postModel->validate())
        {


            $postModel->modify_date        = date("Y-m-d H:i:s",time());;
            $postModel->modify_staff_id   = Yii::$app->user->id;




            //创建Region
            $this->insertOrUpdateToCustTable($postModel, $model);

            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));
            return $this->redirect(  $last_url);


            //return Yii::$app->request->getReferrer();
           // return $this->redirect(['classify','attr_type_spec_id' =>$attr_type_spec_id]);

        }



        // 父区域编码
        $parent_region_id = 0;

        $regionList      = $this->getParentRegionTypes($parent_region_id);




        // 初始化全部的图片
        $uploadModel = new UploadForm();


        $domainTypes   = $this->getDomains('cust', 'cust_type_id');
        $domainSources = $this->getDomains('cust', 'cust_source_id');

        return $this->renderAjax('createmodal',
            [
                'update'  => 1,
                'domainTypes'  => $domainTypes,
                'domainSources' => $domainSources,
                'parent_prod_id' => $parent_prod_id,
                'p1' =>$p1,
                'model' => $model,
                'uploadModel' => $uploadModel,
                'attr_type_spec_id' =>$attr_type_spec_id,
                'attrSpecs' => $attrSpecs,
                'regionList' =>$regionList]);
    }

    public function actionCreate($attr_type_spec_id=null, $parent_prod_id = null, $last_url = null)
    {

        $domainTypes = [];
        $domainSources = [];

        // 初始化类型
        $model = new Cust();//客户
        $orderModel = new Order();//订单

        $model->province = 10;
        $model->city = 16;
        $model->region_id = 27;//区域编码

        if ($model->load(Yii::$app->request->post())&& $orderModel->load(Yii::$app->request->post())
            && $model->validate()
        &&$orderModel->validate())
        {
//            Yii::trace("=====================              ============");
//            Yii::trace($model);
//            Yii::trace($model->parent_id);

           // $model->parent_region_id  = 0;
            $model->create_date        = date("Y-m-d H:i:s",time());;
            $model->create_staff_id   = Yii::$app->user->id;
            $model->modify_date        = date("Y-m-d H:i:s",time());;
            $model->modify_staff_id   = Yii::$app->user->id;
            $model->state               = '301';



            //创建Region
            $this->insertOrUpdateToCustTable($model,null,$orderModel);

            if ($last_url)
            {
                return $this->redirect($last_url);
            }

            return $this->redirect(Yii::$app->request->referrer);
          //  return $this->goBack();

            //return $this->redirect(Yii::$app->request->getReferrer());
          //  return $this->redirect(['classify','attr_type_spec_id' =>$attr_type_spec_id]);

        }

        // 查询所有该产品的特性规格
        $attrSpecs         = $this->getAttrSpecs($attr_type_spec_id);
        $orderAttrSpecs    = $this->getAttrSpecs('30001');
        $custSources       = $this->getCustSources(-1);

        // 父区域编码
        $parent_region_id = 0;

        $regionList      = $this->getParentRegionTypes($parent_region_id);


        $p1 = [];

        // 初始化全部的图片
        $uploadModel = new UploadForm();


        $domainTypes   = $this->getDomains('cust', 'cust_type_id');
        $domainSources = $this->getDomains('cust', 'cust_source_id');


        return $this->render('create',
                            [
                                'custSources'  =>$custSources,
                                'orderModel'  =>$orderModel,
                                'orderAttrSpecs'  => $orderAttrSpecs,
                                'domainTypes'  => $domainTypes,
                                'domainSources' => $domainSources,
                                'parent_prod_id' => $parent_prod_id,
                                'p1' =>$p1,
                                'model' => $model,
                                'uploadModel' => $uploadModel,
                                'attr_type_spec_id' =>$attr_type_spec_id,
                                'attrSpecs' => $attrSpecs,
                                'regionList' =>$regionList,
                                ]);
    }


    public function actionSite($parent_region_id=null)
    {
        $query = new Region();
        $model = $query->getCityList($parent_region_id);

        echo Html::tag('option','选择区域', ['value'=>'empty']) ;
        foreach($model as $value=>$name)
        {
            echo Html::tag('option',Html::encode($name),array('value'=>$value));
        }
    }

    public function actionDelete($id, $attr_spec_type_id=null)
    {

        try{
            $this->deleteCust($id);
           // Yii::$app->getAuthManager()->remove($model->item);
            Yii::$app->session->setFlash('success', Yii::t('region', 'Been saved.'));
        }catch (IntegrityException $e){
            Yii::$app->session->setFlash('success', Yii::t('region', '删除失败.'));
          //  return $this->redirect(Yii::$app->request->getReferrer());
        }

        return $this->redirect(['classify','attr_spec_type_id' => $attr_spec_type_id]);
    }

    public function deleteCust($id)
    {
        $cust = Cust::find()->where(['id'=>$id])->one();
        if($cust)$cust->delete();
    }


    /*通过prod-id获取全部的产品属性实例*/
    public function  getAttrInstByID($id=null )
    {

        $model=[];
        $query = CustExternalAttr::find()->alias('a');
        $query->joinWith('attrSpecs  AS b');
        $query->joinWith('images  AS c');


        $query->where(['a.cust_id' => $id , 'b.attr_spec_type_id' => 2]);
        $models = $query->all();

        foreach ($models as $key => $values)
        {
            $model[$values->attrSpecs['attr_spec_id']][] = $values->images['url'] . $values->images['image_name'];
        }

        return $model;
    }

    /*通过prod-id获取全部的产品实例*/
    public function getCust($id=null)
    {
        // 初始化最重要的产品实例字段
        $model = new Cust();


        $query = Cust::find()->alias('a');
        $query->joinWith('users  AS f');
        $query->joinWith('modifyUsers  AS g');
        $query->joinWith('regions  AS b');
        $query->joinWith('parentRegions  AS c');
        $query->joinWith('custExternalAttrs  AS e');
        $query->where(['a.id' => $id ]);
        $models = $query->all();

        $model = $models[0];
        foreach($models[0]->custExternalAttrs as $attrSpec)
        {

            Yii::trace($attrSpec->attr_spec_id);
            if ($attrSpec->attr_spec_id==3)
            {
                $model->attrSpecs[$attrSpec->attr_spec_id] = substr($attrSpec->content,0,2).'***' .substr($attrSpec->content,-1,2) ;

                Yii::trace("^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^>");
                Yii::trace($model->attrSpecs[$attrSpec->attr_spec_id] );
            }
            else
            {
                $model->attrSpecs[$attrSpec->attr_spec_id] = $attrSpec->content;
            }
        }


        return $model;
    }

    // 取出父级区域编码对应的文字
    public function getParentRegionTypes($parent_region_id)
    {
        $query2 = Region::find();
        $query2->where(['parent_region_id' => $parent_region_id ]);
        $regionList      = $query2->orderBy('id')->all();
        return $regionList;
    }

    // 取出区域编码对应的文字
    public function getRegionTypes()
    {

        $regionTypes = [];
        $query = RegionType::find()->alias('a');
        $queryRegionTypes = $query->all();
        foreach ($queryRegionTypes as $queryRegionType)
        {
            $regionTypes[$queryRegionType->id] = $queryRegionType->region_type_name;
        }

        return $regionTypes;
    }


    public function saveFile($file)
    {
        $url = 'uploads/';
        $filelName =  time().rand(100,999) . '.' . $file->extension;
        $file->saveAs($url . $filelName);

        // 将图片地址存入数据库，记录该图片的来源时间和上传人
        $image                = new Image();
        $image->image_name  = $filelName;
        $image->url          = '/' . $url;
        $image->create_date = date("Y-m-d H:i:s",time());
        $image->staff_id     = Yii::$app->user->id;

        $image->save();

        // 获得id
        $imageId = $image->attributes['id'];

        return $imageId;
    }


    public function updateOrderAttr($cust_id, $newModel=null, $oldModel=null)
    {
        $insertOrderModelAttrs=[];

        $i = 0;                       // 批量插入的数量
        $resumes_type_id = 20004;     // 默认为修改描述
        $insertOrderResumes =[];      // 批量插入的数组

        $model = Order::find()->where(['id'=>$oldModel->id])->one();

        $newModel->id = $oldModel->id;

        // 计算日志如何插入
        // 如果员工发生了变化为修改负责人
        if ($model->staff_id!= $newModel->staff_id)
        {
            $resumes_type_id = 20003;
            // 增加备注 这个是百分百有的
            $insertOrderResumes[$i][] = $newModel->id;
            $insertOrderResumes[$i][] = $resumes_type_id;
            $insertOrderResumes[$i][] = $model->state;
            $insertOrderResumes[$i][] = $model->state;
            $insertOrderResumes[$i][] = $newModel->remark;
            $insertOrderResumes[$i][] = $newModel->staff_id;
            $insertOrderResumes[$i][] = Yii::$app->user->id;;
            $insertOrderResumes[$i][] = date("Y-m-d H:i:s",time());

            $i++;
        }



        // 订单结束

            $resumes_type_id = 20008;

            // 增加备注 这个是百分百有的
            $insertOrderResumes[$i][] = $newModel->id;
            $insertOrderResumes[$i][] = $resumes_type_id;
            $insertOrderResumes[$i][] = $model->state;
            $insertOrderResumes[$i][] = $model->state;
            $insertOrderResumes[$i][] = $newModel->remark;
            $insertOrderResumes[$i][] = $newModel->staff_id;
            $insertOrderResumes[$i][] = Yii::$app->user->id;;
            $insertOrderResumes[$i][] = date("Y-m-d H:i:s",time());
            $i++;



      //  $model->state               = $newModel->state ;
        $model->remark              = $newModel->remark  ;
        $model->staff_id           = $newModel->staff_id  ;
       // $model->order_id            = $oldModel->id;
        $model->modify_date        = date("Y-m-d H:i:s",time());;
        $model->modify_staff_id   = Yii::$app->user->id;

        //   更新订单主表
        $model->save();

        // 插入修改履历
        if (!empty($insertOrderResumes))
        {
            Yii::$app->db->createCommand()->batchInsert(OrderResumes::tableName(), ['order_id','resumes_type_id','last_state','next_state','remark','staff_id','create_staff_id','create_date'], $insertOrderResumes)->execute();
        }


        // 开始比较对应的属性值，检查属性是否有需要更新和新增的
        foreach ($newModel->localAttrsInsts as $key => $localAttrInst)
        {
            // 如果实例不存在则新增
            if (!$oldModel->localAttrsInsts[$key])
            {
                // 如果值为空也不插入
                if(!$localAttrInst['content'] && !$localAttrInst['content2'])
                {
                    continue;
                }



                $content  = $localAttrInst['content'];
                $content2 = $localAttrInst['content2'];

                $insertOrderModelAttrs[$i][] = $newModel->id;
                $insertOrderModelAttrs[$i][] = $key;
                $insertOrderModelAttrs[$i][] = $content;
                $insertOrderModelAttrs[$i][] = 0;
                $insertOrderModelAttrs[$i][] = $content2;
                $i++;
            }
            else//存在的话看下数值是否一致，不一致则更新
            {

                //有两段值
                if ($oldModel->localAttrsInsts[$key]['content']!=$localAttrInst['content'])
                {
                    OrderExternalAttr::updateAll(['content' => $localAttrInst['content']], ['id' => $oldModel->localAttrsInsts[$key]['id']]);
                }

                if ($oldModel->localAttrsInsts[$key]['content2']!=$localAttrInst['content2'])
                {
                    OrderExternalAttr::updateAll(['content2' => $localAttrInst['content2']], ['id' => $oldModel->localAttrsInsts[$key]['id']]);
                }

            }


        }

        return $insertOrderModelAttrs;
    }

    /**
     * 新增或者修改 role table
     * @param $newRole
     * @param string $oldRole
     */
    public function insertOrUpdateToCustTable( $newModel, $oldModel=null, $orderAttrModel=null,   $oldOrderAttrModel=null)
    {
        $i = 0;                   // 批量插入的数量
        $insertModelAttrs =[];     // 批量插入的数组
        $insertOrderModelAttrs=[];
        $oldAttrInst = [];  // 旧的产品特性实例

        $ResultContext = '处理成功';

        if($oldModel)
        {
            // 更新客户内容
            $model = Cust::find()->where(['id'=>$newModel->id])->one();
            $model->modify_date        = date("Y-m-d H:i:s",time());;
            $model->modify_staff_id   = Yii::$app->user->id;
            $model-> cust_name         = $newModel->cust_name;
            $model-> cust_type_id     = $newModel->cust_type_id;
//            $model-> region_id         = $newModel->region_id ;
            $model-> cust_source_id     = $newModel->cust_source_id;
            $model->tel                = $newModel->localAttrsInsts[3]['content'];
            // 不更新备注
          //  $model-> remark             = $newModel->remark;
            $model-> cust_address      = $newModel->cust_address ;
            $model->save();


            // 填写产品特性值
            // 检查产品特性值是否有值，或者有变化， 有变化就更新，原来没有值插入值

            // 构成标准值
            foreach ($model->custExternalAttrs as $key => $attrInst)
            {
                $oldAttrInst[$attrInst->attr_spec_id]['content'] = $attrInst->content;
                $oldAttrInst[$attrInst->attr_spec_id]['id']       = $attrInst->id;
            }


            foreach ($newModel->localAttrsInsts as $key => $localAttrInst)
            {
                // 如果实例不存在则新增
                if (!$oldAttrInst[$key])
                {
    
                    //处理图片类型
                    if ($localAttrInst['attrSpecTypeID']==2)
                    {
                        // 初始化图片对象类
                        $uploadModel = new UploadForm();

                        //取出对应的图片句柄
                        $uploadModel->file = UploadedFile::getInstances($uploadModel, 'file[' . $key . ']');



                        // 审核是否有图片 & 图片是否符合校验标准
                        if ($uploadModel->file  && $uploadModel->validate())
                        {
                            $imageIndex = 0;

                            // 将图片插入表格
                            foreach ($uploadModel->file as $file)
                            {
                                // 获得id
                                $imageId =  $this->saveFile($file) ;

                                if ($imageId)
                                {
                                    $insertModelAttrs[$i][] = $model->id;
                                    $insertModelAttrs[$i][] = $key;
                                    $insertModelAttrs[$i][] = $imageId ;
                                    $insertModelAttrs[$i][] = $imageIndex ;

                                    $i++;
                                    $imageIndex++;
                                }



                                // 构成属性值的更新或者插入语句
                            }

                        }
                    }
                    else
                    {
                        // 如果值为空也不插入
                        if(!$localAttrInst['content'])
                        {
                            continue;
                        }

                        $content = $localAttrInst['content'] ;

                        $insertModelAttrs[$i][] = $model->id;
                        $insertModelAttrs[$i][] = $key;
                        $insertModelAttrs[$i][] = $content ;
                        $insertModelAttrs[$i][] = 0 ;
                        $i++;
                    }

                }
                else//存在的话看下数值是否一致，不一致则更新
                {
                    if ($localAttrInst['attrSpecTypeID']==2)
                    {
                        // 初始化图片对象类
                        $uploadModel = new UploadForm();

                        //取出对应的图片句柄
                        $uploadModel->file = UploadedFile::getInstances($uploadModel, 'file[' . $key . ']');

                        // 审核是否有图片 & 图片是否符合校验标准
                        if ($uploadModel->file  && $uploadModel->validate())
                        {
                            $imageIndex = 0;

                            // 将图片插入表格
                            foreach ($uploadModel->file as $file)
                            {
                                // 获得id
                                $imageId =  $this->saveFile($file) ;

                                if ($imageId)
                                {
                                    custExternalAttr::updateAll(['content' => $imageId], ['id' => $oldAttrInst[$key]['id']]);


                                }
                                // 构成属性值的更新或者插入语句
                            }

                        }
                    }

                    else
                    {
                        if ($oldAttrInst[$key]['content']!=$localAttrInst['content'])
                        {
                            custExternalAttr::updateAll(['content' => $localAttrInst['content']], ['id' => $oldAttrInst[$key]['id']]);
                        }
                    }

                }

            }

            // 如果订单数组有值则更新订单
            $insertOrderModelAttrs = $this->updateOrderAttr($newModel->id,$orderAttrModel, $oldOrderAttrModel);
            $ResultContext = '客源订单信息更新成功！';

        }
        else
        {
            // 如果是订单的客源创建，以订单的备注为客户的备注
            if ($orderAttrModel)
            {
                if ($orderAttrModel->remark)
                {
                    $newModel->remark  = $orderAttrModel->remark;
                }

            }

            //如果电话号码不存在直接返回错误 暂时不判断

            // 检查客户是否存在，通过电话号码
            $searchModel = new CustSearch();
            $oriModel = $searchModel->searchByAccNbr($newModel->localAttrsInsts['3']);

            //如果客户存在，考虑是不是进行更新履历即可
            if ($oriModel)
            {
                // 获得已经存在的id
                $id = $oriModel->id;

                // 判断客户是否有在用订单，有订单的话不能执行插入，只进行订单跟进记录更新，直接返回；
                // 没有订单可以进行下一步处理
                $searchOrderModel = new OrderSearch();
                $orderOriModel = $searchOrderModel->getValidOrderByCustID($id);

                // 客户存在有效订单
                if ($orderOriModel)
                {

                    // 更新订单 只更新更新时间和更新人
                    $orderOriModel->modify_staff_id   = Yii::$app->user->id;
                    $orderOriModel->modify_date        = date("Y-m-d H:i:s",time());
                    $orderOriModel->save();

                    // 更新订单履历 插入一条新的履历
                    $orderResumesModel = new OrderResumes();//履历更新

                    if (!$newModel->orderRemark)
                    {
                        $orderResumesModel->remark = $newModel->remark;
                    }
                    else
                    {
                        $orderResumesModel->remark  = $newModel->orderRemark;
                    }

                    $orderResumesModel->order_id           = $orderOriModel->id;
                    $orderResumesModel->staff_id           = $orderOriModel->staff_id;
                    $orderResumesModel->resumes_type_id   = Yii::$app->params['RESUMES_TYPE_UPDATE_DESC'];
                    $orderResumesModel->create_staff_id   = Yii::$app->user->id;
                    $orderResumesModel->create_date        = date("Y-m-d H:i:s",time());
//                    $orderResumesModel->remark              = $newModel->orderRemark;
                    $orderResumesModel->last_state          = $orderOriModel->state;
                    $orderResumesModel->next_state          = $orderOriModel->state;

                    $orderResumesModel->save();

                    $ResultContext = '用户订单已经存在，本次只更新了对应的跟进记录！';
                    Yii::$app->session->setFlash('success', $ResultContext);
                    return;



                }

            }
            else
            {// 如果客户不存在，才进行插入

                $newModel->tel                = $newModel->localAttrsInsts[3]['content']; //电话号码

                $newModel->save();

                // 获得插入的id
                $id = $newModel->attributes['id'];
            }




            // 如果有获取订单信息的话对订单表order进行插入 否则只插入客户表cust
            if ($orderAttrModel)
            {
                $state=$_POST['state'];
                if(empty($orderAttrModel->input_time)){//是否输入时间，没有就用当前时间
                    $orderAttrModel->input_time=date("Y-m-d H:i:s",time());
                }

                // 初始化类型
                $orderModel        = new Order();
//                $orderModel->region_id        =  $newModel->region_id;
                if($orderAttrModel->staff_id){
                    $orderModel->staff_id          = $orderAttrModel->staff_id;
                }else{
                    $orderModel->staff_id          = Yii::$app->user->id;
                }

                $orderModel->object_id         = $id;
                $orderModel->state              = $state;
                $orderModel->object_type_id    = 1;  // 楼盘
                $orderModel->order_type_id     = 1;  // 楼盘放租
                $orderModel->modify_staff_id   = Yii::$app->user->id;
                $orderModel->create_staff_id   = Yii::$app->user->id;
                $orderModel->create_date        = date("Y-m-d H:i:s",time());
                $orderModel->modify_date        = date("Y-m-d H:i:s",time());
                $orderModel->input_time        = $orderAttrModel->input_time;


                if ($orderAttrModel->region_id){
                    $orderModel->region_id  = $orderAttrModel->region_id;
                }



                if (!$newModel->orderRemark)
                {
                    $orderModel->remark  = $newModel->remark;
                }
                else
                {
                    $orderModel->remark  = $newModel->orderRemark;
                }


                $orderModel->save();

                $ordrId = $orderModel->attributes['id'];

                // 增加属性

                if ($orderAttrModel->localAttrsInsts) {
                    foreach ($orderAttrModel->localAttrsInsts as $key => $orderExternalAttr) {

                        //处理图片类型
                        if ($orderExternalAttr['attrSpecTypeID'] == 2) {

                            // 初始化图片对象类
                            $uploadModel = new UploadForm();

                            //取出对应的图片句柄
                            $uploadModel->file = UploadedFile::getInstances($uploadModel, 'file[' . $key . ']');

                            // 审核是否有图片 & 图片是否符合校验标准
                            if ($uploadModel->file && $uploadModel->validate()) {
                                $imageIndex = 0;

                                // 将图片插入表格
                                foreach ($uploadModel->file as $file) {
                                    // 获得id
                                    $imageId = $this->saveFile($file);

                                    $insertOrderModelAttrs[$i][] = $ordrId;
                                    $insertOrderModelAttrs[$i][] = $key;
                                    $insertOrderModelAttrs[$i][] = $imageId;
                                    $insertOrderModelAttrs[$i][] = $imageIndex;
                                    $insertOrderModelAttrs[$i][] = $key;
                                    $i++;
                                    $imageIndex++;

                                    // 构成属性值的更新或者插入语句
                                }

                            }

                            continue;
                        }

                        // 如果值为空也不插入
                        if (!$orderExternalAttr['content']&&!$orderExternalAttr['content2']) {
                            continue;
                        }
                        //多区域选择$content是个数组
                        if ($orderExternalAttr['attrSpecTypeID'] == 1){
                            foreach($orderExternalAttr['content'] as $content){
                                $content2 = $orderExternalAttr['content2'];
                                $insertOrderModelAttrs[$i][] = $ordrId;
                                $insertOrderModelAttrs[$i][] = $key;
                                $insertOrderModelAttrs[$i][] = $content;
                                $insertOrderModelAttrs[$i][] = 0;
                                $insertOrderModelAttrs[$i][] = $content2;
                                $i++;
                            }
                        }
                        else
                        {
                            $content = $orderExternalAttr['content'];
                            $content2 = $orderExternalAttr['content2'];

                            $insertOrderModelAttrs[$i][] = $ordrId;
                            $insertOrderModelAttrs[$i][] = $key;
                            $insertOrderModelAttrs[$i][] = $content;
                            $insertOrderModelAttrs[$i][] = 0;
                            $insertOrderModelAttrs[$i][] = $content2;
                            $i++;
                        }



                    }
                }

                $remarkd=$_POST['remarkd'];
                if($state==30001){
                    $orderResumesModel = new OrderResumes();//履历更新

                    $orderResumesModel->order_id           = $ordrId;
                    $orderResumesModel->staff_id           = $orderModel->staff_id;
                    $orderResumesModel->resumes_type_id   = 20001;
                    $orderResumesModel->create_staff_id   = Yii::$app->user->id;
                    $orderResumesModel->create_date        = date("Y-m-d H:i:s",time());
                    $orderResumesModel->remark              = $orderModel->remark;
                    $orderResumesModel->last_state          = 30004;
                    $orderResumesModel->next_state          = 30001;

                    $orderResumesModel->save();

                    // 如果订单的操作员工不是本人需要生成一条修改负责人的动作
                    if ($newModel->orderStaffID!=Yii::$app->user->id)
                    {
                        $orderResumesModel = new OrderResumes();//履历更新

                        $orderResumesModel->order_id           = $ordrId;
                        $orderResumesModel->staff_id           = $orderModel->staff_id;
                        $orderResumesModel->resumes_type_id   = Yii::$app->params['RESUMES_TYPE_UPDATE_STAFF'];
                        $orderResumesModel->create_staff_id   = Yii::$app->user->id;
                        $orderResumesModel->create_date        = date("Y-m-d H:i:s",time());
                        $orderResumesModel->remark              = '修改了负责人';
                        $orderResumesModel->last_state          = 30001;
                        $orderResumesModel->next_state          = 30001;

                        $orderResumesModel->save();
                    }




                }elseif($state==30003){
                    $orderResumesModel = new OrderResumes();//履历更新建立一条新的

                    $orderResumesModel->order_id           = $ordrId;
                    $orderResumesModel->staff_id           = $orderModel->staff_id;
                    $orderResumesModel->resumes_type_id   = 20001;
                    $orderResumesModel->create_staff_id   = Yii::$app->user->id;
                    $orderResumesModel->create_date        = date("Y-m-d H:i:s",time());
                    $orderResumesModel->remark              = $orderModel->remark;
                    $orderResumesModel->last_state          = 30004;
                    $orderResumesModel->next_state          = 30001;

                    $orderResumesModel->save();

                    $orderResumesModel = new OrderResumes();//履历更新作废这条

                    $orderResumesModel->order_id           = $ordrId;
                    $orderResumesModel->staff_id           = $orderModel->staff_id;
                    $orderResumesModel->resumes_type_id   = 20001;
                    $orderResumesModel->create_staff_id   = Yii::$app->user->id;
                    $orderResumesModel->create_date        = date("Y-m-d H:i:s",time());
                    $orderResumesModel->remark              = $remarkd;
                    $orderResumesModel->last_state          = 30001;
                    $orderResumesModel->next_state          = 30003;

                    $orderResumesModel->save();
                }


            }




            if ($newModel->localAttrsInsts)
            {
                foreach ($newModel->localAttrsInsts as $key => $custExternalAttr   )
                {

                    //处理图片类型
                    if ($custExternalAttr['attrSpecTypeID']==2)
                    {

                        // 初始化图片对象类
                        $uploadModel = new UploadForm();

                        //取出对应的图片句柄
                        $uploadModel->file = UploadedFile::getInstances($uploadModel, 'file[' . $key . ']');

                        // 审核是否有图片 & 图片是否符合校验标准
                        if ($uploadModel->file  && $uploadModel->validate())
                        {
                            $imageIndex = 0;

                            // 将图片插入表格
                            foreach ($uploadModel->file as $file)
                            {
                                // 获得id
                                $imageId =  $this->saveFile($file) ;

                                $insertModelAttrs[$i][] = $id;
                                $insertModelAttrs[$i][] = $key;
                                $insertModelAttrs[$i][] = $imageId ;
                                $insertModelAttrs[$i][] = $imageIndex ;

                                $i++;
                                $imageIndex++;

                                // 构成属性值的更新或者插入语句
                            }

                        }

                        continue;
                    }

                    // 如果值为空也不插入
                    if(!$custExternalAttr['content'])
                    {
                        continue;
                    }

                    $content = $custExternalAttr['content'] ;

                    $insertModelAttrs[$i][] = $id;
                    $insertModelAttrs[$i][] = $key;
                    $insertModelAttrs[$i][] = $content ;
                    $insertModelAttrs[$i][] = 0 ;
                    $i++;

                }
            }

            $ResultContext = '创建客源订单成功！';
        }

        // 如果插入数组不为空则执行插入
        if (!empty($insertModelAttrs))
        {
            Yii::$app->db->createCommand()->batchInsert(CustExternalAttr::tableName(), ['cust_id','attr_spec_id','content','sort'], $insertModelAttrs)->execute();
        }

        if (!empty($insertOrderModelAttrs))
        {
            Yii::$app->db->createCommand()->batchInsert(OrderExternalAttr::tableName(), ['order_id','attr_spec_id','content','sort','content2'], $insertOrderModelAttrs)->execute();
        }

        Yii::$app->session->setFlash('success', $ResultContext);

        return;

    }

    public function getDomains($domainTableName = null, $domainFieldName = null)
    {
        $where     = []; // 查询条件
        $domainOut = []; //返回的domain数组，以code为索引，name为值的数组
        $where['domain_table_name'] = $domainTableName;
        $where['domain_field_name'] = $domainFieldName;
        $query = Domain::find();
        $domains = $query->where($where)->all();


        foreach ($domains as   $values)
        {
            $domainOut[$values->domain_code ] = $values->domain_name;
        }

        return $domainOut;
    }

//    public function actionIndex()
//    {
//        $menus = SystemEvent::GetAdminMenu();
//        if(Yii::$app->request->isAjax){
//            return '<script>OA_Menus='.Json::encode($menus).'</script>';
//        }
//        return $this->renderPartial('index',['menus'=>$menus]);
//    }




}
